<?php

namespace backend\controllers;

use app\models\ArcFiles;
use app\models\ArcluyinFiles;
use common\helps\UploadFiles;
use Yii;
use yii\data\Pagination;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;
use app\models\search\ArcluyinFilesSearchModel;
use common\helps\Arc;
use kartik\dialog\Dialog;
use yii\helpers\Url;
use yii\bootstrap\Modal;
use yii\helpers\Html;
use common\models\User;
use moonland\phpexcel\Excel;
use function yii\db\all;

/**
 * 语音识别录音文件
 */
class ArcluyinFilesController extends CommonController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ArcFiles models.
     * @return mixed
     */
    public function actionIndex()
    {
    	$searchModel = new ArcluyinFilesSearchModel();//实现分业查询
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    	$query = $dataProvider->query;
    	$countQuery = clone $query;
    	$pages = new Pagination(['totalCount' => $countQuery->count()]);
    	if(isset($_POST['pageSize'])){//设置了参数，就把参数给pageSize session
    		setcookie('pageSize',$_POST['pageSize']);
    	}
    	if(!empty($_COOKIE['pageSize'])){
    		$pages->pageSize = (int)$_COOKIE['pageSize'];
    	}else{
    		$pages->pageSize = 5;
    	}
    	$models = $query->offset($pages->offset)
    	->limit($pages->limit)
    	->all();
    	$dataProvider->pagination = $pages;
    	return $this->render('index', [
    			'models' => $models,
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    			'pages' => $pages,
    	]);
    }

    /**
     * Displays a single ArcFiles model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * 录音文件的上传，用的是爱arc_file表类型为1的文件
     * @return \yii\web\Response|string
     */
    public function actionCreate()
    {
        $model = new ArcluyinFiles();
        
        if (Yii::$app->request->isPost) {
        	$model->file = UploadedFile::getInstances($model, 'file');
        	if (UploadFiles::upload($model,new ArcluyinFiles())) {
        		// 文件上传成功
        		echo Yii::$app->session->setFlash('success','上传成功！');
        	}
        }
        return $this->render('create', ['model' => $model]);
    }
    
    /**
     * Updates an existing ArcFiles model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing ArcFiles model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }
    
    
   	/**
   	 * 语音识别的动作，实现录音文件的语音识别
   	 * @return \yii\web\Response|string
   	 */
    public function actionArc($id)
    {
    	$model = $this->findModel($id);
    	$this->layout = false;//取消main的布局，只有自身的内容布局
    	return $this->render('arc',['absBasePath'=>$this->absBasePath,'model'=>$model]);
    }
    
   	/**
   	 * 防止提交到阿里云后台语音识别有阻塞发生
   	 * @return \yii\web\Response|string
   	 */
    public function actionSendAsrPost($id)
    {
    	$model = $this->findModel($id);
    	$res = Arc::sendAsrPost('https://nlsapi.aliyun.com/recognize?model=chat',$this->absBasePath.$model->filepath);
		$result = json_decode($res);
		$model->arcresult = $result->result;
		$model->arcresult_type = 1;
		$saveRes = $model->save();
		echo $result->result;
    }
    
    /**
     * 
   	 * 将数据导出到本地，格式为exel/csv
     * @param unknown $id
     */
    public function actionDownload($id)
    {
    	$model = ArcluyinFiles::find()->all();
    	Excel::export([
    			'models'=>$model,
    			'fileName'=>date('Ymd').'_'.'Export',
    			'columns'=>[
    					'id',
    					'name',
    					['attribute' => 'time',
				             'value'=>
				                function($model){
				                    return  date('Y-m-d H:i:s',$model->time);   //主要通过此种方式实现
				                },
			            ],
    					'arcresult',
//     					'arc_classify:name'
    			],
				'headers'=>[
						'id'  =>  '文件编号',
						'name'  =>  '名称',
						'time'  =>  '上传时间',
						'arcresult'  =>  '识别结果',
						'arc_classify'  =>  '所用分类',
				]	
    	]);
    }
    
   	/**
   	 * 读取wayMi的列表信息
   	 * 有两种方法，
   	 * 1.从WayMi的数据库直接拿到数据
   	 * 2.从WayMi的后台接口返回的json字符串拿到数据，然后解析、显示
   	 * @return \yii\web\Response|string
   	 */
    public function actionWmIndex()
    {
    	return $this->render('wm-index');
    }

    /**
     * Finds the ArcFiles model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ArcFiles the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ArcluyinFiles::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}